<template>
    <nly-content-wrapper class="content-warpper-2">
        <div class="content-header-2">
            <!--按钮-->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <!-- <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="!isCollected">
                            <div class="btns" @click="tabMyCollect">
                                <a-icon class="btns-icon" type="heart" />
                                <div class="btns-text">我的关注</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="isCollected">
                            <div class="btns" @click="tabMyCollect">
                                <a-icon class="btns-icon" style="color:red" type="heart" />
                                <div class="btns-text">退出关注</div>
                            </div>
                        </a-col> -->
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="AddItem">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="EdiItem">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">编辑</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:clue:disable')">
                            <div style="position:relative">
                                <div class="btns" @click="disable">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                                <div style="position:absolute;width:2px;height:36px;border-radius:6px;background:#ccc;top:0px;right:0px;"></div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:clue:import')">
                            <div class="btns" @click="importFile">
                                <a-icon class="btns-icon" type="import" />
                                <div class="btns-text">导入</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:clue:export')">
                            <div class="btns" @click="() => (exportVisible = true)">
                                <a-icon class="btns-icon" type="export" />
                                <div class="btns-text">导出</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="!isCollected">
                            <div class="btns" @click="collectAdd()">
                                <a-icon class="btns-icon" type="heart" />
                                <div class="btns-text">关注客户</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="collectOut()">
                                <a-icon class="btns-icon" type="frown" />
                                <div class="btns-text">取消关注</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:clue:receive')">
                            <div class="btns" @click="receive()">
                                <a-icon class="btns-icon" type="tags" />
                                <div class="btns-text">领用</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:clue:distribution')">
                            <div class="btns" @click="distribution()">
                                <a-icon class="btns-icon" type="branches" />
                                <div class="btns-text">分配</div>
                            </div>
                        </a-col>
                        <!-- <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="onShowSerch">
                                <a-icon class="btns-icon" type="file-search" />
                                <div class="btns-text">查询</div>
                            </div>
                        </a-col> -->
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="showMySet">
                                <a-icon class="btns-icon" type="setting" />
                                <div class="btns-text">自定义列</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="GetCustomizeList">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">同步设置</div>
                            </div>
                    </a-col>
                    </a-col>
                    
                </a-row>
            </div>
            <!-- 查询方案 -->
            <a-col :span="24">
                <div class="search-btn-box-gw">
                    <div class="item-small" ref="planLi">
                        <ul>
                            <li class="item-plan" :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                            <li class="item-plan" :title="item.searchName" :class="item.id == planActive?'active':''" v-for="(item,index) in userSearchList" :key="index" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            <li class="item-plan" @click="onShowSerch">
                                <!-- <a-icon class="icon-searh-btn" type="file-search" /> 查询 -->
                                自定查询
                                <a-icon class="icon-searh-btn" type="search" />
                            </li>
                        </ul>
                    </div>
                    <div class="item-small-down" v-if="showDownPlan" @click="showDownPlanFun">
                        <a-icon v-if="iconDirection" type="down" />
                        <a-icon v-else type="up" />
                    </div>
                </div>
            </a-col>
            <!-- 查询方案结束 -->
            <!-- <nly-row class="col-12">
                <nly-row class="col-12">
                    <fixed-condition :conditions="conditions" :FixedConditionKeys="FixedConditionKeys" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></fixed-condition>
                    <div class="mb-1">
                        <nly-button @click="showFunction" variant="info" button-class="mr-2">
                            <i :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />{{ show ? "折 叠" : "展 开" }}
                        </nly-button>
                        <nly-button variant="info" @click="onSerch" button-class="mr-2" :disabled="loading">查询</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="reset" :disabled="loading">重置</nly-button>
                        <nly-button variant="info" @click="showUsModal" button-class="mr-2">保存常用查询</nly-button>
                    </div>
                </nly-row>
            </nly-row> -->
            <!-- <dynamic-condition :conditions="conditions" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition> -->

            <a-drawer class="mySet" title="自定义列" width="520" height="300" @close="onMySetClose" :visible="mySetVisible">
                <a-checkbox-group v-model="mySetcheckedListLocal" :options="mySetplainOptions" @change="onMySetChange" />
                <nly-col xs="12" sm="12" class="form-inline align-self-start mt-3" style>
                    <nly-button-group>
                        <nly-button variant="danger" @click="onMySetClose" button-class="mr-2">关闭</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="saveMyShow">确定</nly-button>
                    </nly-button-group>
                </nly-col>
            </a-drawer>
            <nly-container fluid></nly-container>
        </div>
        <!-- 功能操作 -->
        <!-- <div>
            <a-button type="primary" class="crm-btn" @click="tabMyCollect" v-show="!isCollected"><i class="fas fa-flag fa-flag-more"></i>我的关注</a-button>
            <a-button type="" class="crm-btn" @click="tabMyCollect" v-show="isCollected"><i class="fas fa-flag fa-flag-more"></i>退出关注</a-button>
            <a-button type="primary" class="crm-btn" @click="collectAdd" v-show="!isCollected">关注客户</a-button>
            <a-button type="primary" class="crm-btn" @click="collectOut">取消关注</a-button>
            <a-button type="primary" class="crm-btn" @click="receive" v-if="permissions.includes('crm:clue:receive')">领用</a-button>
            <a-button type="primary" class="crm-btn" @click="distribution" v-if="permissions.includes('crm:clue:distribution')">分配</a-button>
            <a-button type="primary" class="crm-btn" @click="EdiItem" v-if="permissions.includes('crm:clue:edit')">编辑</a-button>
            <a-button type="primary" class="crm-btn" @click="AddItem" v-if="permissions.includes('crm:clue:add')">新增</a-button>
            <a-dropdown type="primary">
                <a-menu slot="overlay">
                    <a-menu-item key="2" @click="disable" v-if="permissions.includes('crm:clue:disable')">
                        <a-icon type="user" />删除
                    </a-menu-item>

                    <a-menu-item key="3" @click="importFile" v-if="permissions.includes('crm:clue:import')">
                        <a-icon type="user" />导入
                    </a-menu-item>
                    <a-menu-item key="5" @click="() => (exportVisible = true)" v-if="permissions.includes('crm:clue:export')">
                        <a-icon type="user" />导出
                    </a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px">
                    更多
                    <a-icon type="down" />
                </a-button>
            </a-dropdown>
            <i class="fa fa-fw fa-cog fieldSet " @click="showMySet"></i>
        </div> -->

        <nly-content>
            <!-- 列表 -->
            <a-table id="crm_tb" :columns="columns" :rowClassName="rowClassName" :data-source="data" :scroll="{ x: 500, y: 500 }" bordered :pagination="pagination" :loading="loading" @change="onTableChange" :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}" >
                <a slot="crmName" slot-scope="text, record" @click="goToDetail(record,'touch')">
                    <i :class="record.collectId > 0 ? 'fas fa-heart fa-heart-red':'fas fa-flag fa-flag-white'"></i>
                    {{text}}
                </a>
                <a slot="crmNo" slot-scope="text, record" @click="goToDetail(record,'touch')">
                    {{text}}
                </a>
                <div slot="shareType" slot-scope="text,record" v-if="text">
                    <span v-if="userInfo.id == record.collarUserId">已共享给‘{{record.shareUserName}}’</span>
                    <span v-else>由‘{{record.collarUserName}}’共享</span>
                </div>
                <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                    <a-input v-model="crmNameValue" :placeholder="`搜索${column.title}`" style="width: 188px; margin-bottom: 8px; display: block;" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
                    <a-button size="small" style="width: 90px; margin-right: 8px" @click="() => handleReset(clearFilters)">
                        重置
                    </a-button>
                    <a-button type="primary" icon="search" size="small" style="width: 90px;" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                        搜索
                    </a-button>
                </div>
                <a-icon slot="filterIcon" type="filter" theme="filled" :style="{ color: '#444',marginRight:'5px' }" />
                <div slot="lastTouchSummary" slot-scope="text,record">
                    <div style="cursor:pointer">
                        <a-tooltip placement="left">
                            <template slot="title">
                                {{text}}
                            </template>
                            {{text}}
                        </a-tooltip>
                    </div>
                </div>
            </a-table>
            <!-- modal 弹窗  -->
            <drag-modal :title="editItem.id ? '编辑客户资料' : '新增客户资料'" :visible="ModalVisible" @ok="onSubmit" @cancel="hideModal" class="add-or-edit-modal">
                <div class="min-box">
                    <!-- 动态 表单  -->
                    <dynamic-form :formPostData="formPostData" :initFormData="initFormData" :errors="formErrors" :isOk="isFromShow" :blurEventMap="blurEventMap"></dynamic-form>
                    <!-- 是否自动释放  -->
                    <div class="form-inline">
                        <div class="col col-lg-12 col-sm-12 col-12 zidongshifang">
                            <form-select v-if="isAutomaticrelease" :error="formErrors['formPostData.isRelease']" :required="true" labelStyle="" title="自动释放" rightClass="myRightClass" v-model="formPostData.isRelease" :dataList="[{ key: true, title: '是' },{ key: false, title: '否' }]"></form-select>
                        </div>
                    </div>
                </div>
                <template slot="footer">
                    <div>
                        <a-button type="primary" @click="onSubmit">确认</a-button>
                        <a-button @click="hideModal" class="margin-left-10">关闭</a-button>
                    </div>
                </template>
            </drag-modal>
            <!-- 常用查询名称编辑框 -->
            <a-modal title="保存常用查询" :visible="UsVisible" @ok="UserSearchSave" @cancel="hideUsModal">
                <nly-row class="form-inline" v-show="isOk">
                    <form-input title="名称" rightStyle="flex-grow:1;" class="ml-1 mb-1" style="flex:0.8;" :error="myUsErrors['userSearchEditItem.searchName']" :required="true" v-model="userSearchEditItem.searchName"></form-input>
                </nly-row>
            </a-modal>

            <a-modal v-model="exportVisible" title="导出客户数据文件" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                    <a-radio-group v-model="exportRadioValue">
                        <p>
                            <a-radio value="1">导出所选客户：{{exportValue || 0}}条</a-radio>
                        </p>
                        <p>
                            <a-radio value="2">导出符合条件客户：{{pagination.total || 0}}条</a-radio>
                        </p>
                    </a-radio-group>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" icon="download" @click="exportCrmData">导出</a-button>
                    <a-button key="back" @click="() => (exportVisible = false)" icon="close">取消</a-button>
                </template>
            </a-modal>

            <a-modal v-model="importVisible" title="导入客户资料" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;">
                    <p>
                        第1步：下载客户导入模板
                        <a href="javascript:;" @click="downloadTemplate" style="font-size: 12px;color: blue;">点击下载模板</a>
                    </p>
                    <p>
                        第2步：*上传文档
                        <label>
                            <input type="file" id="file" name="file" style="padding-left: 15px;" class="form-file" />
                        </label>
                    </p>
                    <div>
                        <span>第3步:导入资料至</span>
                        <label style="padding-left: 15px;">
                            <input name="Fruit" type="radio" checked />线索公海
                        </label>
                    </div>
                    <div style="margin-top: 15px;">
                        <p>导入说明</p>
                        <p>1.上传存储有客户资料的Excel文件，大小不超过5M</p>
                        <p>2.设置Excel里的列与系统中的列的对应关系</p>
                        <p>3.如果客户名称已存在，则将联系人信息追加到此客户的联系人后面</p>
                        <p>4.开始导入</p>
                    </div>
                    <div style="margin-top: 25px;">
                        <p>
                            <sapn style="color:red;font-size: 18px;">*</sapn>'所属地区'栏目格式说明
                        </p>
                        <p>1.可以传入省市区的组合(例：a.四川省 b.四川省/成都市 c.四川省/成都市/锦江区 )</p>
                        地区助手：
                        <a-cascader placeholder="请选择地区" change-on-select show-search :field-names="{ label: 'areaName', value: 'areaCode',children: 'children'}" @change="onAreaChange" :options="regions" />
                        '所属地区'：<sapn style="color:red;">{{ areaText }}</sapn>
                    </div>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="importCrm">下一步</a-button>
                    <a-button key="back" @click="() => (importVisible = false)">取消</a-button>
                </template>
            </a-modal>

            <a-modal v-model="filedVisible" title="匹配导入字段" centered on-ok="handleok" width="650px">
                <a-spin :spinning="isSpinning" tip="导入中...">
                    <div style="margin-left:30px;height: 400px;overflow-y: scroll;">
                        <a-table :columns="filedColumns" :data-source="filedData" :pagination="false" bordered>
                            <template slot="crmFiled" slot-scope="text, record, index">
                                <select-group title="下拉效果" size="small" selectStyle="width:80%;" labelStyle="display: none;" :dataList="text" :prekey="'crm' + index" v-model="record.crmCode"></select-group>
                            </template>
                        </a-table>
                    </div>
                </a-spin>

                <template slot="footer">
                    <a-button v-show="!isSpinning" key="submit" type="primary" @click="importData">导入</a-button>
                    <a-button v-show="!isSpinning" key="back" @click="() => (filedVisible = false)">取消</a-button>
                </template>
            </a-modal>

            <a-modal v-model="resultVisible" title="导入结果" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                    <p>新增客户数：{{impotrResult.insertCustomerNum || 0}}</p>
                    <p>更新客户数：{{impotrResult.updateCustomerNum || 0}}</p>
                    <p>导入失败数：{{ (impotrResult.failNum) || 0}}</p>
                    <p>如果您需要导入失败的记录及原因，请点击下载按钮</p>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" icon="download" @click="downloadImportResult">下载</a-button>
                    <a-button key="back" @click="() => (resultVisible = false)" icon="close">取消</a-button>
                </template>
            </a-modal>

            <a-modal v-model="exportVisible" title="导出客户数据文件" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                    <a-radio-group v-model="exportRadioValue">
                        <p>
                            <a-radio value="1">导出所选客户：{{exportValue || 0}}条</a-radio>
                        </p>
                        <p>
                            <a-radio value="2">导出符合条件客户：{{pagination.total || 0}}条</a-radio>
                        </p>
                    </a-radio-group>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" icon="download" @click="exportCrmData">导出</a-button>
                    <a-button key="back" @click="() => (exportVisible = false)" icon="close">取消</a-button>
                </template>
            </a-modal>

            <a-modal v-model="userModal" centered title="分配客户给" width="300px">
                <div style="height: 400px;overflow-y:scroll;">
                    <a-input-search style="margin-bottom: 8px" placeholder="输入用户名称" @change="onChange" />
                    <div v-show="treeAShow">
                        <a-tree :selected-keys="selectedUserKeys" :tree-data="userSearchData" :expanded-keys="expandedUserKeys" @expand="expanedChange" :defaultExpandAll="true" @select="onUserSelect" :checkable="false" :show-icon="true">
                            <a-icon slot="user" type="user" />
                        </a-tree>
                    </div>
                    <div v-show="treeBShow">
                        <a-tree :selected-keys="selectedUserKeys" :tree-data="userAllData" :defaultExpandAll="true" :checkable="false" @select="onUserSelect" :show-icon="true">
                            <a-icon slot="user" type="user" />
                        </a-tree>
                    </div>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="distributionSave">确定</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="() => {this.userModal=false}">关闭</a-button>
                </template>
            </a-modal>

            <!-- 查询方案弹窗 -->
            <a-modal class="search-wrapper-box-crm" :visible="visibleSearchPlan" title="查询" @cancel="cancel" width="1000px">
                <div class="content-box">
                    <div class="left-box">
                        <a-row class="btn-wrapper">
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?UserSearchSave():''">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">保存</div>
                                </div>
                            </a-col>
                            <a-col :span="6">
                                <div class="btns" @click="showUsModal(2)">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">另存</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?showUsModal(1):''">
                                    <a-icon class="btns-icon" type="edit" />
                                    <div class="btns-text">修改</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?onUserSearchDelete({key:planActive}):''">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                            </a-col>
                        </a-row>
                        <div class="plan-list">
                            <ul>
                                <li :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                                <li v-for="(item,index) in userSearchList" :key="index" :class="item.id == planActive?'active':''" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            </ul>
                        </div>
                    </div>
                    <div class="right-box">
                        <a-tabs default-activeKey="1" @change="callback">
                            <a-tab-pane key="1" tab="查询条件">
                                <dynamic-condition v-if="visibleSearchPlan" :checkable="true" :conditions="conditions" :show="true" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition>
                            </a-tab-pane>
                        </a-tabs>
                    </div>
                </div>
                <template slot="footer">
                    <div>
                        <!-- <div style="float:left">
                            <a-checkbox :checked="planActive == defaultPlanActive?true:false" @change="inPagePlanSave">
                                下次以此方案进入
                            </a-checkbox>
                        </div> -->
                        <a-button type="primary" @click="onSerch">查询</a-button>
                        <a-button @click="cancel" class="margin-left-10">取消</a-button>
                    </div>
                </template>
                <a-modal :title="nowPlanType==1?'保存为另一个方案':'修改方案标题'" :visible="saveASVisible" width="400px" centered @cancel="saveAsPlanClose">
                    <a-input v-model="saveAsName" placeholder="请输入查询方案名称"></a-input>
                    <template slot="footer">
                        <div>
                            <a-button type="primary" @click="saveAsPlanSubmit(1)">确定</a-button>
                            <a-button @click="saveAsPlanClose" class="margin-left-10">取消</a-button>
                        </div>
                    </template>
                </a-modal>
            </a-modal>
            <drawerCrm :drawerVisible.sync="drawerVisible" :routeUrl="routeUrl" :title="drawerTitle" :dataItem="dataItem" @collectOut="collectOut" @collectAdd="collectAdd" @dealSave="dealSave" @openShareBox="openShareBox" @release="release" @distribution="distribution" @receive="receive"></drawerCrm>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { getPhonetic } from "@/api/common/py";
import {
    PageList,
    Save as SaveCustomer,
    receive,
    release,
    dealSave,
    potentialSave,
    saveShare,
    distributionSave,
    disable,
    enable,
    collectAdd,
    collectOut,
    combineSave,
    exportData,
    importTemplate,
    getExcelFiled,
    importData,
    downloadFailCause
} from "@/api/crm/customer";
import { initValidator, checkAll } from "@/utils/validator/validator";
import { TreeDataOffice } from "@/api/office";
import { Controlwidth } from "@/utils/antTableComponents";
import { officeUserListToTree, searchInTreeData, areaPageListToTreeForId } from "@/utils/tree";
import { clearValue, clearKeys } from "@/utils/tool/object";
import getDate from "@/utils/tool/date";
import { treeList } from "@/api/area";

import dynamicList from "@/mixins/dynamicList";
import drawerCrm from "@/components/Crm/drawer";
import MiddleUtils from '@/utils/middle-utils'
const checkedModelList = [];

export default {
    mixins: [dynamicList],
    data () {
        const filedColumns = [
            {
                title: "Excel字段",
                dataIndex: "excelFiled",
                key: "excelFiled",
                align: "left"
            },
            {
                title: "系统字段",
                dataIndex: "crmFiled",
                key: "crmFiled",
                align: "left",
                scopedSlots: { customRender: "crmFiled" }
            }
        ];
        //表格 头部 可伸缩
        return {
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------

            //gw 2021年8月16日11:04:08
            visibleSearchPlan: false,
            //gw 2021年8月16日11:04:16
            searchType: 0,     //0:线索客户 1.潜在客户 2.成交客户  3.联系人 4.联系人记录  5.商机 
            source: "crm",
            crmType: 0,        //客户大类 0:线索客户  1.潜在客户 2.成交客户     
            isCheck: true,      //是否校验
            isNotTasking: true, //是否排除 外呼任务的 客户
            FixedConditionKeys: ["crmName", "phonetic"],  //固定的搜索条件的Key
            excludeDefineFields: ["collarUserId", "officeName", "shareType"],     //排除的启用字段
            customRenderCode: ["crmName", "shareType", 'crmNo'], //table 使用插槽的列
            selectedUserKeys: [], //用户选择key
            selectedUserName: "", //用户tree选择name
            selectedMergeKeys: [], //客户合并key
            userAllData: [], //所有用户tree数据
            expandedUserKeys: [], //用户tree展开keys
            userSearchData: [], //用户tree搜索数据
            treeAShow: false, //搜索用户tree
            treeBShow: true, //用户tree
            importVisible: false, //导入文件弹窗
            filedVisible: false, //字段匹配弹窗
            resultVisible: false, //导入结果弹窗
            excelFiled: [], //excel字段
            impotrResult: {}, //导入结果
            isSpinning: false, //导入加载框
            exportVisible: false, //导出弹窗
            exportValue: 0, //要导出选中的数量
            exportRadioValue: "1", //导出redio值
            crmCheckedDatas: [], //客户选中的数据
            userModal: false, //分配客户
            filedColumns,
            filedData: [],
            //行政区信息
            regions: [],
            //选择地区
            areaText: '',

            drawerVisible: false,//客户详情抽屉
            routeUrl: '',
            drawerTitle: '',
            dataItem: {},
            crmNameValue: null,
            rowClassName: (record, index) => {
                if (record.clickActive) {
                    return 'click-table-active'
                }
            },
        };
    },
    components: {
        drawerCrm,//客户系统抽屉显示详情
    },
    watch: {
        $route: {
            handler (nv, ov) {
                //离开路由关闭 右侧详情抽屉
                this.drawerVisible = false;
            },
            deep: true
        },
    },
    activated () {
        //通过消息跳转过来需要弹出 侧边详细客户信息
        let id = this.$route.query.id;
        if (id) {
            detail({ id }).then(response => {
                if (response.code === 200) {
                    this.goToDetail(response.data, 'crm')
                }
            }).catch(error => { });
        }
    },
    mounted () {
        this.areaTree();
        TreeDataOffice({ isLoadUser: 2 }).then(response => {
            const { data } = response;
            const childrenNav = [];
            officeUserListToTree(data, childrenNav, "0");
            this.userAllData = childrenNav;
            this.userSearchData = childrenNav;
        });
        MiddleUtils.$on('syncList', (value) => {
            if(this.$route.path == '/crm/customer/list'){
                console.log("刷新syncList---线索客户");
                this.PageList();
            }
        })
    },
    updated () {
        Controlwidth("crm_tb", 50);
    },
    computed: {
        // 是否释放
        isAutomaticrelease: function () {
            const { permissions, crmType } = this;
            let isShow = false;
            if (
                (crmType == 0 && permissions.includes("crm:clue:automaticrelease"))
                || (crmType == 1 && permissions.includes("crm:potential:automaticrelease"))
                || (crmType == 2 && permissions.includes("crm:deals:automaticrelease"))
            ) {
                isShow = true;
            }
            return isShow;
        }
    },
    methods: {
        //地区选择事件
        onAreaChange (value, selectedOptions) {
            this.areaText = selectedOptions.map(o => o.areaName).join('/');
        },
        //加载 区域数据
        areaTree () {
            treeList()
                .then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        const childrenNav = [];
                        areaPageListToTreeForId(data, childrenNav, 0);
                        console.log("加载 区域数据:", childrenNav);
                        this.regions = childrenNav;
                    }
                })
                .catch(error => { });

        },
        //跳转到 客户详情
        goToDetail (item, tabkey) {
            const { permissions } = this;
            if (!this.customerId && permissions.includes("crm:clue:edit")) {
                // this.$router.push(`/crm/customer/detail/${item.crmName}/${item.id}/${tabkey}`)
                this.drawerVisible = true;
                this.routeUrl = window.location.host + `/crm/customer/detail/${item.crmName}/${item.id}/${tabkey}`;
                this.drawerTitle = item.crmName;
                this.dataItem = item;
                this.$forceUpdate();
                //给点击的行一个颜色
                this.data.map(d => {
                    this.$set(d, 'clickActive', false)
                });
                this.$set(item, 'clickActive', true)
            }
        },
        //添加
        AddItem () {
            this.GetCustomizeList();//刷新动态字段
            const { formPostData, formErrors } = this;
            clearKeys(formErrors);
            formPostData.isRelease = true;
            this.isFromShow = true;
            this.ModalVisible = true;
            console.log("AddItem_formErrors->", formErrors)
        },
        //编辑
        EdiItem () {
            this.GetCustomizeList();//刷新动态字段
            if (this.selectedKeys.length != 1) {
                this.$message.warn("请选择一条客户数据");
                return false;
            }
            const item = this.crmCheckedDatas.find(f => f.id == this.selectedKeys[0]);
            this.goToDetail(item, 'crm');
        },
        onSerch () {
            const { postData } = this;
            postData.page.current = 1;
            this.PageList();
            this.cancel();
        },
        // 获取列表
        PageList (backId) {
            this.selectedKeys = [];
            const { postData, onOffDefineFields } = this;
            console.log("潜在客户——搜索条件：", onOffDefineFields);
            postData.dtos = onOffDefineFields;
            postData.page.size = this.pagination.pageSize;
            this.loading = true;
            PageList(postData).then(response => {
                this.loading = false;
                console.log("获取潜在客户列表", response);
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    //转换自定义数据数据
                    this.defineFieldsAddToData(records);

                    this.data = records;
                    console.log("转换后的数据：records", records);
                    Object.assign(this.pagination, {
                        total
                    });

                    //客户保存成功过后直接跳入详情页面
                    if (backId) {
                        const item = this.data.find(f => f.id == backId);
                        this.goToDetail(item, 'crm');
                    }
                } else {
                    this.data = [];
                    this.$message.error(response.message);
                }
            }).catch(error => {
                this.loading = false;
            });
        },
        //获取中文拼音首字母，并赋值拼音码
        getPhonetic () {
            const { formPostData } = this;
            if (!formPostData.phonetic) {
                getPhonetic({ keyword: formPostData.crmName }).then(response => {
                    if (response.code === 200) {
                        this.$set(this.formPostData, "phonetic", response.data || response.message);
                    }
                })
            }
        },
        //提交表单
        onSubmit () {
            const {
                isCheck,
                crmType,
                formRules,
                formPostData,
                formErrors,
                onOffDefineFields
            } = this;
            //全部校验一次
            checkAll(this, formRules, formPostData, formErrors);
            if (Object.keys(formErrors).length > 0) {
                this.isFromShow = false;
                this.$nextTick(function () {
                    this.isFromShow = true;
                });
                return false;
            }
            //自定义字段 重组
            let defineFieldsSets = onOffDefineFields.filter(f => f.dataType == 2);
            let defineFields = {};
            //获取重组后的自定义集合
            this.getDefineFields(defineFields, formPostData, defineFieldsSets);
            Object.assign(formPostData, {
                isCheck,
                crmType,
                defineFields: JSON.stringify(defineFields)
            });
            formPostData.isCustomer = 1;
            SaveCustomer(formPostData).then(response => {
                if (response.code === 200) {
                    this.$message.success("保存成功");
                    this.hideModal();
                    this.PageList(response.data);
                    this.planActive = 0;
                    this.onUserSearchChange();
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //客户tabale check触发
        selection (keys, info) {
            this.selectedKeys = keys;
            console.log("rowKeys", info);
            this.crmCheckedDatas = info;
            this.exportValue = info.length;
        },
        //客户合并tabale check触发
        mergeSelection (keys, info) {
            this.selectedMergeKeys = keys;
            console.log(keys, info);
        },
        checkCrmKey () {
            if (this.selectedKeys.length < 1) {
                this.$message.warn("没有选择客户");
                return false;
            }
            return true;
        },
        //我的关注 切换
        tabMyCollect () {
            this.isCollected = !this.isCollected;
            Object.assign(this.postData, {
                isCollected: this.isCollected
            });
            this.PageList();
        },
        //关注客户
        collectAdd (id) {
            if (id) {
                collectAdd([id]).then(response => {
                    if (response.code == 200) {
                        this.$message.success("关注成功");
                        this.PageList();
                    } else {
                        this.$message.error(response.message);
                    }
                });
            } else {
                if (this.checkCrmKey()) {
                    collectAdd(this.selectedKeys).then(response => {
                        if (response.code == 200) {
                            this.$message.success("关注成功");
                            this.PageList();
                            this.selectedKeys = [];
                        } else {
                            this.$message.error(response.message);
                        }
                    });
                }
            }
        },
        //取消关注
        collectOut (id) {
            if (id) {
                collectOut([id]).then(response => {
                    if (response.code == 200) {
                        this.$message.success("取消关注成功");
                        this.PageList();
                    }
                });
            } else {
                if (this.checkCrmKey()) {
                    collectOut(this.selectedKeys).then(response => {
                        if (response.code == 200) {
                            this.$message.success("取消关注成功");
                            this.PageList();
                            this.selectedKeys = [];
                        } else {
                            this.$message.error(response.message);

                        }
                    });
                }
            }
        },
        //领用客户
        receive (id) {
            if (id) {
                this.selectedKeys = [id];
            }
            if (this.checkCrmKey()) {
                let _this = this;
                this.$confirm({
                    title: '提示',
                    content: "确定要领用吗？",
                    okText: "确定",
                    cancelText: "取消",
                    onOk () {
                        receive(_this.selectedKeys).then(response => {
                            if (response.code == 200) {
                                _this.$message.success(response.message);
                                _this.drawerVisible = false;//关闭抽屉窗口
                                setTimeout(_this.PageList(), 1);
                            } else {
                                _this.$message.error(response.message);
                            }
                        });
                    },
                    onCancel () {
                    },
                });
            }
        },
        //分配弹窗
        distribution (id) {
            if (id) {
                this.selectedKeys = [id];
            }
            if (this.checkCrmKey()) {
                this.userModal = true;
                this.treeAShow = false;
                this.treeBShow = true;
            }
        },
        //分配客户
        distributionSave () {
            if (this.checkCrmKey()) {
                if (this.selectedUserKeys[0].indexOf("user") != -1) {
                    distributionSave({
                        type: 1,
                        collarUserId: this.selectedUserKeys[0].split("_")[0],
                        collarUserName: this.selectedUserName,
                        ids: this.selectedKeys.toString()
                    }).then(response => {
                        if (response.code == 200) {
                            this.$message.success("分配成功");
                            this.drawerVisible = false;//关闭抽屉窗口
                            this.PageList();
                            this.selectedKeys = [];
                            this.userModal = false;
                        } else {
                            this.$message.error(response.message);
                        }
                    });
                } else {
                    this.$message.warn("请选择用户");
                }
            }
        },
        //删除
        disable () {
            if (this.checkCrmKey()) {
                let _this = this;
                this.$confirm({
                    title: "提示",
                    content: '您确定要删除吗？',
                    onOk () {
                        disable({ ids: _this.selectedKeys.toString(), status: 2 }).then(
                            response => {
                                if (response.code == 200) {
                                    _this.$message.success("删除成功");
                                    _this.PageList();
                                    _this.selectedKeys = [];
                                } else {
                                    _this.$message.success(response.message);
                                }
                            }
                        );
                    },
                    cancelText: '取消',
                    onCancel () {
                    },
                });
            }
        },
        //导出客户数据
        exportCrmData () {
            const { postData, onOffDefineFields } = this;
            console.log("客户系统——搜索条件：", onOffDefineFields);
            postData.dtos = onOffDefineFields;
            if (this.exportRadioValue == 1) {
                if (this.exportValue == 0) {
                    this.$message.warn("请选择要导出的客户");
                    return false;
                }
                postData.crmIds = this.selectedKeys;
            } else {
                if (this.pagination.total == 0) {
                    this.$message.warn("没有客户数据不能导出");
                    return false;
                }
                postData.crmIds = null;
            }
            exportData(postData).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "客户资料.xls");
                document.body.appendChild(link);
                link.click();
                this.resultVisible = false;
                this.exportVisible = false;
                this.selectedKeys = [];
            });
        },
        //导入
        importCrm () {
            //上传execl文件 匹配字段
            //this.$refs["merge-modal"].show();
            const formData = new FormData();
            let excelFile = document.getElementById("file").files[0];
            if (excelFile == null || excelFile.name == "") {
                this.$error({
                    title: "错误提示",
                    content: "文件不能为空"
                });
                return false;
            }

            var AllImgExt = ".xls|.xlsx|";
            var extName = excelFile.name
                .substring(excelFile.name.lastIndexOf("."))
                .toLowerCase();
            if (AllImgExt.indexOf(extName + "|") == -1) {
                this.$error({
                    title: "错误提示",
                    content: "文件格式错误，请上传xls、xxlsx类型文件"
                });
                return false;
            }

            let size = excelFile.size;
            size = size / (1024 * 1024);
            if (size >= 5) {
                this.$error({
                    title: "错误提示",
                    content: "文件过大,不能超过5M"
                });
                return;
            }

            formData.append("file", excelFile);
            formData.append("source", this.source);
            getExcelFiled(formData).then(response => {
                if (response.code == 200) {
                    this.importVisible = false;
                    let exlFiled = response.data.excelFiled;
                    if (exlFiled == null || exlFiled.length == 0) {
                        this.$error({
                            title: "错误提示",
                            content: "文件没有数据"
                        });
                        return;
                    }
                    this.filedVisible = true;
                    this.filedModelFooter = true;
                    this.excelFiled = exlFiled;
                    let crmFiled = response.data.crmFiled;
                    let cFiled = [];
                    let lFiled = [];
                    let tableFiledData = [];
                    cFiled.push({ key: '', title: '  ' });
                    for (let i = 0; i < crmFiled.length; i++) {
                        if (crmFiled[i].title.includes("联系人.")) {
                            lFiled.push(crmFiled[i]);
                        } else {
                            cFiled.push(crmFiled[i]);
                        }
                    }

                    console.log("获取表头", exlFiled);
                    for (let i = 0; i < exlFiled.length; i++) {
                        let item = crmFiled.find(f => f.title == exlFiled[i]);
                        tableFiledData.push({
                            excelFiled: exlFiled[i],
                            crmFiled: [
                                { groupTitle: "客户资料", data: cFiled },
                                { groupTitle: "联系人资料", data: lFiled }
                            ],
                            crmCode: item && item.key
                        });
                        this.filedData = tableFiledData;
                    }
                }
            });
        },
        //下载模版
        downloadTemplate () {
            const {source} = this;
            importTemplate({source}).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "导入客户资料模板.xls");
                document.body.appendChild(link);
                link.click();
            });
        },
        //导入数据
        importData () {
            this.isSpinning = true;
            this.filedModelFooter = false;
            let crmCodes = this.filedData.map(f => f.crmCode);
            console.log(crmCodes);
            const formData = new FormData();
            formData.append("file", document.getElementById("file").files[0]);
            formData.append("excelFiled", this.excelFiled);
            formData.append("dbFiled", crmCodes);
            formData.append("companyType", "isCustomer");
            importData(formData).then(response => {
                if (response.code == 200) {
                    this.impotrResult = response.data;
                    this.resultVisible = true;
                    this.filedVisible = false;
                    this.isSpinning = false;
                    this.PageList();
                } else {
                    this.filedVisible = false;
                    this.isSpinning = false;
                    this.$message.error("导入失败，请联系管理员");
                }
            });
        },
        //下载导入结果
        downloadImportResult () {
            console.log("下载导入结果", this.impotrResult);
            const formData = new FormData();
            formData.append("excelField", this.impotrResult.excelField);
            formData.append("failCause", this.impotrResult.failCause);
            formData.append("failData", JSON.stringify(this.impotrResult.failData));
            downloadFailCause(formData).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "导入失败的数据和原因.xls");
                document.body.appendChild(link);
                link.click();
                this.resultVisible = false;
            });
        },
        //导入弹窗
        importFile () {
            this.importVisible = true;
            var obj = document.getElementById('file');
            obj.outerHTML = obj.outerHTML;
        },
        //用户tree展开
        expanedChange (key, info) {
            this.expandedUserKeys = key;
        },
        //用户tree选择
        onUserSelect (key, info) {
            this.selectedUserKeys = key;
            this.selectedUserName = info.node.title;
            console.log(key, info);
        },
        //用户搜索
        onChange (e) {
            const value = e.target.value;
            console.log(value);
            if (value) {
                this.treeAShow = true;
                this.treeBShow = false;
                const keys = [];
                const treeData = searchInTreeData(
                    keys,
                    this.userAllData,
                    "title",
                    value
                );
                this.userSearchData = treeData;
                this.expandedUserKeys = keys;
            } else {
                this.treeAShow = false;
                this.treeBShow = true;
                //this.areaTreeData = treeAreaData;
                this.expandedUserKeys = [];
            }
        },
        //gw 2021年8月16日11:51:51
        cancel () {
            //置空临时查询条件
            // if (this.planActive == 0) {
            //     setTimeout(() => {
            //         this.onOffDefineFields.forEach(item => {
            //             item.value = '';
            //         });
            //     }, 200)
            // }
            this.visibleSearchPlan = false;
        },
        onShowSerch () {
            this.visibleSearchPlan = true;
        },
        //客户名称搜索
        handleReset (clearFilters) {
            //重置
            clearFilters();
            this.crmNameValue = '';
            this.onOffDefineFields.forEach(res => {
                if (res.code == 'crmName') {
                    res.value = this.crmNameValue;
                }
            })
            this.PageList()
        },
        handleSearch (key, confirm, col) {
            //table搜索
            confirm();
            console.log(key)
            console.log(confirm)
            console.log(col)
            if (col == 'crmName') {
                this.crmNameValue = key[0];
            }

            this.onOffDefineFields.forEach(res => {
                if (res.code == 'crmName') {
                    res.value = this.crmNameValue;
                }
            })
            this.PageList()
        },
    }
};
</script>
<style lang="less">
    .mySet {
        .ant-checkbox-group-item {
            margin-bottom: 0.5rem !important;
            width: 110px !important;
        }
    }

    @import '~@/style/crm.less';
    // .zidongshifang {
    //     .ant-select-selection__rendered,
    //     .ant-select-selection-selected-value,
    //     .ant-select-selection {
    //         height: 28px;
    //         line-height: 28px;
    //     }
    // }
</style>
